// Copyright 2009 Pigasus.
// GNU GPL v2.
// Author: John Zhang and Jordan Rupprecht.

#include "servers.h"

#include <stdio.h>

#include "common.h"

using namespace std;
  
Servers::Servers() {
  next_server_index = 0;
  servers = NULL;
}

Servers::~Servers() {
  if (servers) delete servers;
}

Servers::Servers(const Servers& s) {
  next_server_index = 0;
  if (s.servers) {
    servers = s.servers->Clone();
    has_password.resize(servers->GetSize());
    for (int i = 0; i < static_cast<int>(has_password.size()); i++) {
      has_password[i] = false;
    }
  }
}

Servers* Servers::Clone() {
  return new Servers(*this);
}

void Servers::SetServers(List &servers_) {
  if (servers) delete servers;
  servers = servers_.Clone();
}

Map* Servers::GetNextServer() {
  if (!servers || !servers->GetSize()) {
    // Servers not set!!!
    return NULL;
  }
  // Basic round-robin scheduling. TODO: Weighted round robin.
  Map* ret = (Map*)((*servers)[next_server_index]);

  // Send password here, if we haven't already for this server.
  if (!has_password[next_server_index]) {
    FILE *p;
    char ignore[20];
    char *err;
    string buffer;
    string user = (*(string*)(ret->Get("user")));
    string host = (*(string*)(ret->Get("host")));
    string password = (*(string*)(ret->Get("password")));
  
    debug("Sending password (user: %s, host: %s).\n", user.c_str(),
          host.c_str());
  
    // Send SSH keys.
    buffer = "./sendkey.sh " + user + " " + host + " " + password 
      + " `cat pig_rsa.pub` &> /dev/null" ;
    p = popen(buffer.c_str(), "r");
    while (!feof(p)) err = fgets(ignore, sizeof(ignore), p);
    pclose(p);
    has_password[next_server_index] = true;
  }

  next_server_index = (next_server_index + 1) % servers->GetSize();

  return ret;
}
